<?php
# Copyright © 2017 Nichlas Severinsen
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.


session_start();

$config = include('config/config.php');

$db = new PDO(
  'mysql:host='.$config['hostname'].';dbname='.$config['database'],
  $config['username'],
  $config['password']);

$is_logged_in = false;

if(isset($_SESSION['username']) && isset($_SESSION['session_key'])){
  $sql = $db->prepare("SELECT session_key FROM user WHERE username=?");
  $sql->execute(array($_SESSION['username']));
  $row = $sql->fetch(PDO::FETCH_ASSOC);

  if($_SESSION['session_key'] == $row['session_key']){
    $is_logged_in = true; 
  }
}

if(isset($_COOKIE['username']) && isset($_COOKIE['session_key'])){
  $sql = $db->prepare("SELECT session_key FROM user WHERE username=?");
  $sql->execute(array($_COOKIE['username']));
  $row = $sql->fetch(PDO::FETCH_ASSOC);

  if($_COOKIE['session_key'] == $row['session_key']){
    $_SESSION['session_key'] = $_COOKIE['session_key'];
    $_SESSION['username'] = $_COOKIE['username'];
    $is_logged_in = true; 
  }
}

if($is_logged_in === false){
  header("Location: ./login.php");
}

?>

<html lang = "en">
  <head>
    <title>OB2 | Login</title>
    <link href="chota.min.css" rel="stylesheet">
  </head>
  <body>
    </br>
    <!--
    <div class="is-center is-marginless">
      <h2 class="is-marginless">Online Bookmarks 2</h2>
    </div>
    <div class="is-center is-marginless">
    Logged in as <?php echo $_SESSION['username'] ?>
    </div> -->
    <div class="container is-full-width">
      <div class="row">
        <div class="col">
          <div class="card is-center">.col</div>
        </div>
      </div>   
    </div>      
    <?php
    
    


    ?>
  </body>
</html>

